<?php

class FlujosController extends GxController {

    public function filters() {
        return array(
            'accessControl',
        );
    }

    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('minicreate', 'create', 'update', 'Combos', 'tipoflujos', 'guardaRequeridos', 'verficiaRequeridos', 'Requeridos'),
                'users' => array('@'),
            ),
            array('allow',
                'actions' => array('admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id, 'Flujos'),
        ));
    }

    public function actionCreate() {
        $model = new Flujos;

        $this->performAjaxValidation($model, 'flujos-form');
        Controller::registrar_scrips();
        if (isset($_POST['Flujos'])) {
            $model->setAttributes($_POST['Flujos']);

            if ($model->save()) {
                if (Yii::app()->getRequest()->getIsAjaxRequest())
                    Yii::app()->end();
                else {
                    $this->guardaAdicionales($model->FLUJOID);
                    $this->redirect(array('view', 'id' => $model->FLUJOID));
                }
            }
        }

        $this->render('create', array('model' => $model));
    }

    private function guardaAdicionales($flujoId, $accion = "crea") {
        $connection = Yii::app()->db;
        if ($accion == "edita") {
            $sql = "delete from FLUJOS_REQUERIDOS where FLUJOID = $flujoId";
            $connection->createCommand($sql)->execute();
        }
        $camposElegidos = trim($_POST["camposElegidos"], ",");
        $camposElegidos = explode(",", $camposElegidos);
        switch ($_POST["Flujos"]["FLUJOTIPO"]) {
            case 'Conteo':
                foreach ($camposElegidos as $row) {
                    $sql = "insert into FLUJOS_REQUERIDOS(FLUJOID,ALSID) VALUES($flujoId,$row)";
                    $connection->createCommand($sql)->execute();
                }
                break;
            case 'Rango':
                foreach ($camposElegidos as $row) {
                    $sql = "insert into FLUJOS_REQUERIDOS(FLUJOID,ALSID) VALUES($flujoId,$row)";
                    $connection->createCommand($sql)->execute();
                }
                break;
            case 'Requerido':
                $sql = "insert into FLUJOS_REQUERIDOS(FLUJOID,ALSID,ALSIDREQUERIDO) select $flujoId,TEMPORALINT1,TEMPORALINT3 from temporal 
                WHERE temporalindice = '{$_POST["timestamp"]}' and temporalint1 is not null and temporalint3 is not null";
                $connection->createCommand($sql)->execute();
                break;
            default:
                exit("Opción incorrecta");
                break;
        }
        return true;
    }

//fin private function guardaAdicionales($flujoId){

    public function actionUpdate($id) {
        $model = $this->loadModel($id, 'Flujos');

        $this->performAjaxValidation($model, 'flujos-form');
        Controller::registrar_scrips();
        if (isset($_POST['Flujos'])) {
            $model->setAttributes($_POST['Flujos']);
            if ($model->save()) {
                $this->guardaAdicionales($model->FLUJOID, "edita");
                $this->redirect(array('view', 'id' => $model->FLUJOID));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionDelete($id) {
        if (Yii::app()->getRequest()->getIsPostRequest()) {
            $this->loadModel($id, 'Flujos')->delete();

            if (!Yii::app()->getRequest()->getIsAjaxRequest())
                $this->redirect(array('admin'));
        } else
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
    }

    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Flujos');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function actionAdmin() {
        $model = new Flujos('search');
        $model->unsetAttributes();

        if (isset($_GET['Flujos']))
            $model->setAttributes($_GET['Flujos']);

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionCombos() {
        if (trim($_POST["opc"]) == "")
            exit("Opcion incorrecta");
        $connection = Yii::app()->db;
        $sql = "";
        $campo = "<option value=''>Seleccione...</option>";
        switch ($_POST["opc"]) {
            case 'Conteo':
                $tablaNucleo = ($_POST["tipoNucleo"] == "Especifico") ? " NUCLEOSESPECIFICOSALIAS " : " NUCLEOSBASICOSALIAS ";
                $campoNucleo = ($_POST["tipoNucleo"] == "Especifico") ? " nucleo.NCLE_ID " : " nucleo.nclb_id ";
                $sql = "select ali.alsid,ali.alsnombre from ALIAS ali
                    inner join $tablaNucleo nucleo on nucleo.als_id = ali.alsid and $campoNucleo = '{$_POST["nucleo"]}' and nucleo.mod_id = '{$_POST["modulo"]}'
                    inner join modulos modu on modu.modid = nucleo.mod_id
                    order by modu.modorden,nucleo.orden,ali.alsnombre";
                break;
            case 'Rango':
                $tablaNucleo = ($_POST["tipoNucleo"] == "Especifico") ? " NUCLEOSESPECIFICOSALIAS " : " NUCLEOSBASICOSALIAS ";
                $campoNucleo = ($_POST["tipoNucleo"] == "Especifico") ? " nucleo.NCLE_ID " : " nucleo.nclb_id ";
                $sql = "select ali.alsid,ali.alsnombre from ALIAS ali
                    inner join $tablaNucleo nucleo on nucleo.als_id = ali.alsid and $campoNucleo = '{$_POST["nucleo"]}' and nucleo.mod_id = '{$_POST["modulo"]}'
                    inner join modulos modu on modu.modid = nucleo.mod_id
                    order by modu.modorden,nucleo.orden,ali.alsnombre";
                break;
            case 'tipFlujo':
                if ($_POST["val"] == "Basico")
                    $sql = "select NCLBID,NCLBNOMBRE from NUCLEOSBASICOS order by NCLBNOMBRE";
                else if ($_POST["val"] == "Especifico")
                    $sql = "select NCLEID,NCLENOMBRE from NUCLEOSESPECIFICOS order by NCLENOMBRE";
                break;
            case 'moduloFlujo':
                if ($_POST["val"] == "Basico")
                    $sql = "select modu.modid,modu.modnombre from modulos modu
                            inner join nucleosbasicosalias nuBa on nuba.mod_id = modu.modid
                            where nuba.nclb_id = {$_POST["val1"]}
                            group by modu.modid,modu.modnombre,modu.modorden order by modu.modorden";
                else if ($_POST["val"] == "Especifico")
                    $sql = "select modu.modid,modu.modnombre from modulos modu
                            inner join NUCLEOSESPECIFICOSALIAS nuBa on nuba.mod_id = modu.modid
                            where nuba.ncle_id = {$_POST["val1"]}
                            group by modu.modid,modu.modnombre,modu.modorden order by modu.modorden";
                break;
            case 'Requerido':
                $tablaNucleo = ($_POST["tipoNucleo"] == "Especifico") ? " NUCLEOSESPECIFICOSALIAS " : " NUCLEOSBASICOSALIAS ";
                $campoNucleo = ($_POST["tipoNucleo"] == "Especifico") ? " nucleo.NCLE_ID " : " nucleo.nclb_id ";
                $sql = "select ali.alsid,ali.alsnombre from ALIAS ali
                    inner join $tablaNucleo nucleo on nucleo.als_id = ali.alsid and $campoNucleo = '{$_POST["nucleo"]}'
                    inner join modulos modu on modu.modid = nucleo.mod_id 
                    order by modu.modorden,nucleo.orden,ali.alsnombre";
                $camposGenerales = $this->creaOptions($sql, $connection);
                if ($camposGenerales == '0') {
                    echo '0';
                    return;
                }
                $sql = "select ali.alsid,ali.alsnombre from ALIAS ali
                    inner join $tablaNucleo nucleo on nucleo.als_id = ali.alsid and $campoNucleo = '{$_POST["nucleo"]}'
                    inner join modulos modu on modu.modid = nucleo.mod_id and modu.modid = {$_POST["modulo"]}
                    order by modu.modorden,nucleo.orden,ali.alsnombre";
                $campo = $this->creaOptions($sql, $connection);
                if ($campo == '0') {
                    echo '0';
                    return;
                }
                echo $camposGenerales . "|&|" . $campo;
                return;
                break;
        } //fin switch($_POST["opc"]){
        $command = $connection->createCommand($sql);
        $results = $command->queryAll();
        if (count($results) <= 0) {
            echo '0';
            return;
        }
        foreach ($results as $rows) {
            $valor = array_values($rows);
            $campo .="<option value='$valor[0]'>$valor[1]</option>";
        }
        echo $campo;
    }

//fin public function actionCombos() {

    private function creaOptions($sql, $connection) {
        $command = $connection->createCommand($sql);
        $results = $command->queryAll();
        $campo = "";
        if (count($results) <= 0) {
            echo '0';
            return;
        }
        foreach ($results as $rows) {
            $valor = array_values($rows);
            $campo .="<option value='$valor[0]'>$valor[1]</option>";
        }
        return $campo;
    }

//fin private function creaOptions($sql){

    public function actionRequeridos() {
        if (trim($_POST["campo"]) == "" || trim($_POST["time"]) == "" )
            exit("Parametros incorrectos");
        $sql = "select al.alsid,al.alsnombre from temporal tmp
                inner join alias al on al.alsid = tmp.temporalint1
                WHERE tmp.temporalindice = '{$_POST["time"]}' and tmp.temporalint3 = '{$_POST["campo"]}'";
        $connection = Yii::app()->db;
        $command = $connection->createCommand($sql);
        $results = $command->queryAll();
        $campos = "";
        if(count($results) > 0){            
            foreach($results as $alias){
                $alias = array_values($alias);
                $campos .= "<option value='$alias[0]'>$alias[1]</option>";
            } //fin foreach($results as $alias){
        }
        echo $campos;
    }

//fin public function actionRequeridos(){

    public function actiontipoflujos() {
        if (trim($_POST["tipo"]) == "" || trim($_POST["tipoNucleo"]) == "" || trim($_POST["nucleo"]) == "" || trim($_POST["modulo"]) == "")
            exit("Parametros incorrectos");
        $connection = Yii::app()->db;
        $sql = "";
        $tablaNucleo = ($_POST["tipoNucleo"] == "Especifico") ? " NUCLEOSESPECIFICOSALIAS " : " NUCLEOSBASICOSALIAS ";
        $campoNucleo = ($_POST["tipoNucleo"] == "Especifico") ? " nucleo.NCLE_ID " : " nucleo.nclb_id ";
        switch ($_POST["tipo"]) {
            case 'Conteo':
                $sql = "select aliAdi.aeaid,aliAdi.descretiqueta from ALIAS_ETIQUETAS_ADICIONALES aliAdi
                    inner join $tablaNucleo nucleo on nucleo.als_id = aliAdi.als_id and $campoNucleo = '{$_POST["nucleo"]}' and nucleo.mod_id = '{$_POST["modulo"]}'
                    order by aliAdi.orden,aliAdi.descretiqueta";
                $command = $connection->createCommand($sql);
                $results = $command->queryAll();
                $campo = "<option value=''>Seleccione...</option>";
                foreach ($results as $rows) {
                    $valor = array_values($rows);
                    $campo .="<option value='$valor[0]'>$valor[1]</option>";
                }
                break;
            case 'moduloFlujo':
                if ($_POST["val"] == "Basico")
                    $sql = "select modu.modid,modu.modnombre from modulos modu
                            inner join nucleosbasicosalias nuBa on nuba.mod_id = modu.modid
                            where nuba.nclb_id = {$_POST["val1"]}
                            group by modu.modid,modu.modnombre,modu.modorden order by modu.modorden";
                else if ($_POST["val"] == "Especifico")
                    $sql = "select modu.modid,modu.modnombre from modulos modu
                            inner join NUCLEOSESPECIFICOSALIAS nuBa on nuba.mod_id = modu.modid
                            where nuba.ncle_id = {$_POST["val1"]}
                            group by modu.modid,modu.modnombre,modu.modorden order by modu.modorden";
                break;
        } //fin switch($_POST["opc"]){
        echo $campo;
    }

//fin public function actiontipoflujos() {

    public function actionverficiaRequeridos() {
        if (trim($_POST["time"]) == "")
            exit("Parametros incorrectos");
        $connection = Yii::app()->db;
        $sql = "select * from temporal where temporalindice = '{$_POST["time"]}'";
        $command = $connection->createCommand($sql);
        $results = $command->queryAll();
        if (count($results) > 0)
            echo '1';
        else
            echo '0';
        return;
    }

//fin public function actionverficiaRequeridos() {

    public function actionguardaRequeridos() {
        if (trim($_POST["time"]) == "" || trim($_POST["alias"]) == "" || trim($_POST["campo"]) == "")
            exit("Parametros incorrectos");
        $alias = explode(',', $_POST["alias"]);
        $connection = Yii::app()->db;
        $sql = "delete from temporal where temporalindice = '{$_POST["time"]}' and temporalint3 = '{$_POST["campo"]}'";
        $command = $connection->createCommand($sql)->execute();
        foreach ($alias as $ali) {
            if($ali == $_POST["campo"]) continue;
            $sql = "insert into temporal(temporalindice,temporalint1,temporalint3) values({$_POST["time"]},$ali,'{$_POST["campo"]}')";
            $command = $connection->createCommand($sql)->execute();
        }
        echo '1';
    }

//fin public function actionguardaRequeridos() {
}